#include"../main.h"
#include <complex.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <time.h>
#include <sys/wait.h>

int main()
{
    key_t key=ftok("./",66);
    if(key==-1)
    {
        perror("ftok:");
        exit(EXIT_FAILURE);
    }
    int semid=semget(key,2,IPC_CREAT |0666);
    if(semid==-1)
    {
        perror("semget:"); 
        exit(EXIT_FAILURE);
    }
    unsigned short i[]={0,1};
    semctl(semid,0,SETALL,i);

    struct sembuf sembuf;
    sembuf.sem_flg=IPC_NOWAIT;
    sembuf.sem_num=0;
    sembuf.sem_op=0;

    int counter=0;
    pid_t pid= fork();
    if(pid==-1)
    {   
        perror("fork:");
        exit(EXIT_FAILURE);
    }
    if(pid==0)
    {
        while(1)
        {
            sembuf.sem_num=0;
            sembuf.sem_op=-1;
            if(++counter==15)break;
            semop(semid,&sembuf,1);
            printf("f==================\n");
            printf("fork\n");
            printf("f==================\n");
            sembuf.sem_num=0;
            sembuf.sem_op= 1;
            semop(semid,&sembuf,1);
        }
        exit(EXIT_SUCCESS);
    }else
    {
        while(1)
        {   
            sembuf.sem_num=0;
            sembuf.sem_op=-1;
            if(++counter==15)break;
            semop(semid,&sembuf,1);
            printf("==================\n");
            printf("pid=%d\n",getpid());
            printf("==================\n");
            sembuf.sem_num=0;
            sembuf.sem_op= 1;
            semop(semid,&sembuf,1);
        }
        wait(NULL);
    }
    semctl(semid,0,IPC_RMID,NULL);
    return 0;
}

